package com.j2203.service.impl;

import cn.hutool.json.JSONUtil;
import com.j2203.dto.CarInfo;
import com.j2203.entity.*;
import com.j2203.mapper.ShoppingCartMapper;
import com.j2203.service.ShoppingCartService;
import com.j2203.utils.RedisWorker;
import com.j2203.vo.ShoppingCart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    /**
     * redis存储的key
     */
   private final String KEY = "steam";
    /**
     * redis注入
     */
    @Resource(type = StringRedisTemplate.class)
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private RedisWorker redisWorker;

    /**
     * 购物车mapper注入
     */
    @Resource(type = ShoppingCartMapper.class)
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public Game findByIdGame(int gid) {
        Game byIdGame = shoppingCartMapper.findByIdGame(gid);
        return byIdGame;
    }

    @Override
    public ShoppingCart addShoppingCar(int gid,int uid) {

        try {

            log.debug("+++++++++++++++");
            Game games = findByIdGame(gid);
            System.out.println(games);
            double price2 = games.getGprice()*games.getGdiscount();
            CarInfo carInfo = new CarInfo(
                    games.getGid(),games.getGname(),games.getGameimg(),games.getGprice(),price2);
            //redis key steam+用户id
            log.debug("用户详情点击加入购物车");
            String car = JSONUtil.toJsonStr(carInfo);
            Long num = stringRedisTemplate.opsForList().leftPush(KEY+uid, car);
        }catch (Exception e){
            log.debug("用户直接点击购物车，正常方法异常");
        }finally {
            ShoppingCart shoppingCar = getShoppingCar(uid);
            return shoppingCar;

        }

    }

    @Override
    public ShoppingCart getShoppingCar(int uid) {
        List<String> carInfos = stringRedisTemplate.opsForList().range(KEY + uid, 0, -1);
        ShoppingCart shoppingCart = new ShoppingCart();
        ArrayList<CarInfo> car = new ArrayList<>();
        double total = 0;

        for (int i = 0; i < carInfos.size(); i++) {
            CarInfo carInfo = JSONUtil.toBean(carInfos.get(i), CarInfo.class);
            car.add(carInfo);
            total += carInfo.getGprice2();
        }
        shoppingCart.setTotal(total);
        shoppingCart.setCarInfos(car);
        return shoppingCart;
    }

    @Override
    public Gmdetail findByIdgmdetail(int gid) {
        Gmdetail gmdetail = shoppingCartMapper.findByIdgmdetail(gid);
        return gmdetail;
    }

    @Override
    public List<Comment> findAllComment(int gid) {
        List<Comment> comment = shoppingCartMapper.findAllComment(gid);
        return comment;
    }

    private int index = 0;
    @Override
    public int delByIdShoppingCar(int gid, int uid) {
//        List<String> shoppingCar = RedisUtil.getShoppingCar(uid);
        List<String> shoppingCar = stringRedisTemplate.opsForList().range(KEY + uid, 0, -1);
        System.out.println(shoppingCar);
        for (int i = 0; i < shoppingCar.size(); i++) {
            CarInfo carInfo = JSONUtil.toBean(shoppingCar.get(i), CarInfo.class);
            if (carInfo.getGid()==i){
                index = i;
                break;
            }
        }
        String s = shoppingCar.get(index);
        Long remove = stringRedisTemplate.opsForList().remove(KEY + uid, 0, s);
        if (remove != 0){
            return 1;
        }
        return 0;
    }

    @Override
    public int delAllShoppingCar(int uid) {
        Boolean delete = stringRedisTemplate.delete(KEY + uid);
        if (delete){
            return 1;
        }else {
            return 0;
        }
    }

    /**
     * 添加事务保证两张表数据写入的原子性
     * @param uid
     * @return
     */
    @Override
    @Transactional
    public ShoppingCart addOrder(int uid) {
        List<String> list = stringRedisTemplate.opsForList().range(KEY + uid, 0, -1);
        Long oid = redisWorker.orderId("id" + uid);

        //将订单号写入redis便于支付的时候使用
//        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//        LocalDateTime now = LocalDateTime.now();
//        long second = now.toEpochSecond(ZoneOffset.UTC);

        String orderId = JSONUtil.toJsonStr(oid);
        stringRedisTemplate.opsForValue().set(uid+"",orderId,20, TimeUnit.MINUTES);

        //购物车信息集合
        ArrayList<CarInfo> carts = new ArrayList<>();

        double total = 0;
        for (int i = 0; i < list.size(); i++) {

            CarInfo carInfo = JSONUtil.toBean(list.get(i), CarInfo.class);
            total += carInfo.getGprice2();

            //将购物车信息对象存入集合
            boolean add = carts.add(carInfo);

            OrderInfo orderInfo = new OrderInfo(oid,carInfo.getGid(),1,carInfo.getGprice2());
            //写订单信息表
            int i1 = shoppingCartMapper.addOrderInfo(orderInfo);
        }
        Order order = new Order(oid,total,new java.sql.Timestamp(System.currentTimeMillis()),uid,0);
        System.out.println(order);
        //写订单表
        int i = shoppingCartMapper.addOrder(order);

        //清空购物车
        int i1 = delAllShoppingCar(uid);

        ShoppingCart shoppingCart = new ShoppingCart(total,carts);

        return shoppingCart;
    }

    @Override
    public int updateOrder(long oid) {

        int i = shoppingCartMapper.updateOrder(oid);
        return i;
    }


}
